package com.wocai.jrt.orders.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.crypto.SecretKey;
import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.vteba.cache.redis.RedisService;
import com.vteba.utils.cryption.DESUtils;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.investor.service.spi.InvestorService;
import com.wocai.jrt.investor.service.spi.RiskDisclosureService;
import com.wocai.jrt.orders.model.Orders;
import com.wocai.jrt.orders.service.impl.ContactThread;
import com.wocai.jrt.orders.service.spi.ContactService;
import com.wocai.jrt.orders.service.spi.OrdersService;
import com.wocai.jrt.utils.ImgType;
import com.wocai.jrt.utils.MyFileUtils;
import com.wocai.jrt.utils.SmsVerificationUtils;

@Controller
@Scope("prototype")
@RequestMapping("/contact")
public class ContactAction extends GenericAction<Orders> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ContactAction.class);

	@Inject
	private ContactService contactServiceImpl;
	@Inject
	private RiskDisclosureService riskDisclosureServiceImpl;
	@Resource(name = "taskExecutor")
	private TaskExecutor taskExecutor;
	@Inject
	private RedisService<String, String> redisService;// 存放短信验证码
	@Inject
	private InvestorService investorServiceImpl;
	@Inject
	private OrdersService ordersServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss"), true));
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/create")
	public JsonBean create(String orderId, String tokenId) {
		JsonBean jsonBean = new JsonBean();

		try {
			// 发起请求的参数,以后直接用AOP代替
			LOGGER.info("request create contact, orderId=[{}],tokenId=[{}]", orderId, tokenId);

			// 验证tokenId
			String raw = "55ec3040f2def095bc4e66f3&1441542208470";

			// String tokenId =
			// "jG8MJPZFG_tQ77YKbsz7WR7abxEpb2CAqnmBQad-cgC8diabq_mxxQ";
			SecretKey key = DESUtils.genDesedeKey("asdfjklajsaddddduiyuyu24");
			byte[] iv = { 98, -1, 78, 22, 1, -32, -101, 3 };
			String decryptTokenId = DESUtils.desedeDecrypt(tokenId, key, iv);
			if (StringUtils.isBlank(tokenId) || !raw.equals(decryptTokenId)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("tokenId错误！");
				LOGGER.error("tokenId is mistake,tokenId=[{}]", tokenId);
				return jsonBean;
			}

			taskExecutor.execute(new ContactThread(contactServiceImpl, riskDisclosureServiceImpl,
					orderId));

			jsonBean.setCode(1);
			jsonBean.setMessage("创建合同成功！");
			LOGGER.info("request create contact success");

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("创建合同失败！");
			LOGGER.error("request create contact error,msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/recreate")
	public JsonBean recreate(String orderId, String authCode, MultipartFile sign) {
		JsonBean jsonBean = new JsonBean();

		try {
			// 发起请求的参数,以后直接用AOP代替
			LOGGER.info("request recreate contact, orderId=[{}]", orderId);

			if (StringUtils.isBlank(orderId)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("订单id不能为空！");
				return jsonBean;
			}

			if (null == sign) {
				jsonBean.setCode(0);
				jsonBean.setMessage("签名图片不能为空！");
				return jsonBean;
			}

			String mobile = investorServiceImpl.getMobileByOrderId(orderId);

			// 校验手机验证码，固话时绕过判断
			if (!Pattern.compile("[0]{1}[0-9]{2,3}[0-9]{7,8}$").matcher(mobile).matches()) {
				if (!SmsVerificationUtils.check(redisService, mobile,
						SmsVerificationUtils.CONTACT_RECREATE_AUTH, authCode)) {
					jsonBean.setCode(0);
					jsonBean.setMessage("验证码错误！");
					LOGGER.error(
							"request recreate error caused authCode is incorrect, authCode=[{}]",
							authCode);
					return jsonBean;
				}
			}

			// 获取原合同路径
			Orders orderParam = new Orders();
			orderParam.setOrderId(orderId);
			String originalContact = ordersServiceImpl.unique(orderParam).getPaySignUser();

			String signPath = MyFileUtils.uploadImg(sign, ImgType.ORDER);
			Orders order = new Orders();
			order.setContactSignUser(signPath);
			order.setPaySignUser("");

			Orders condition = new Orders();
			condition.setOrderId(orderId);
			ordersServiceImpl.updateBulks(order, condition);
			LOGGER.info("update investor sign path success");

			taskExecutor.execute(new ContactThread(contactServiceImpl, null, orderId,
					ordersServiceImpl, originalContact));

			jsonBean.setCode(1);
			jsonBean.setMessage("合同正在生成中，请稍等...");
			LOGGER.info("request recreate contact success");

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("重新创建合同失败！");
			LOGGER.error("request recreate contact error,msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/createRiskDisclosure")
	public JsonBean createRiskDisclosure(String orderId, String tokenId) {
		JsonBean jsonBean = new JsonBean();

		try {
			// 发起请求的参数,以后直接用AOP代替
			LOGGER.info("request create contact, orderId=[{}],tokenId=[{}]", orderId, tokenId);

			// 验证tokenId
			String raw = "55ec3040f2def095bc4e66f3&1441542208470";

			// String tokenId =
			// "jG8MJPZFG_tQ77YKbsz7WR7abxEpb2CAqnmBQad-cgC8diabq_mxxQ";
			SecretKey key = DESUtils.genDesedeKey("asdfjklajsaddddduiyuyu24");
			byte[] iv = { 98, -1, 78, 22, 1, -32, -101, 3 };
			String decryptTokenId = DESUtils.desedeDecrypt(tokenId, key, iv);
			if (StringUtils.isBlank(tokenId) || !raw.equals(decryptTokenId)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("tokenId错误！");
				LOGGER.error("tokenId is mistake,tokenId=[{}]", tokenId);
				return jsonBean;
			}

			taskExecutor.execute(new ContactThread(null, riskDisclosureServiceImpl, orderId));

			jsonBean.setCode(1);
			jsonBean.setMessage("创建风险揭示书成功！");
			LOGGER.info("request create contact success");

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("创建风险揭示书失败！");
			LOGGER.error("request create contact error,msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}

	@ResponseBody
	@RequestMapping("/sendSms")
	public JsonBean sendSms(String mobile) {
		JsonBean jsonBean = new JsonBean();
		try {

			LOGGER.info("request sendSms, mobile=[{}]", mobile);
			if (null != mobile) {
				boolean result = SmsVerificationUtils.sendSms(redisService, mobile,
						SmsVerificationUtils.CONTACT_RECREATE_AUTH);
				if (result) {
					jsonBean.setCode(1);
					jsonBean.setMessage("发送成功！");
				} else {
					jsonBean.setCode(0);
					jsonBean.setMessage("发送失败！");
				}
			}

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("发送失败！");
			LOGGER.error("sendSms error.msg=[{}]", e.getMessage());
		}

		return jsonBean;
	}

}
